package cn.nexd.app.config.presenter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import com.squareup.okhttp.Request;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import cn.nexd.app.config.Config;
import cn.nexd.app.config.R;
import cn.nexd.app.config.model.Expandable;
import cn.nexd.app.config.model.Mall;
import cn.nexd.app.config.ui.activity.ConfigActivity;
import cn.nexd.app.config.ui.activity.MallListActivity;
import cn.nexd.app.config.util.MD5Util;
import cn.nexd.app.config.util.OkHttpClientManager;
import cn.nexd.app.config.util.ProgressDialogUtils;

/**
 * Created by wangxu on 16/7/19.
 */
public class ConfigPresenter extends BasePresenter<ConfigActivity>{
    private final String TAG = this.getClass().getSimpleName();

    private ArrayList<Expandable> expandable;

    public static final int REQUEST_CODE = 10011;

    private boolean cancel = false;

    private boolean isWifiChecked = false;
    private boolean isBluetoothChecked = false;
    private boolean isMapChecked = false;
    private boolean isRoutePlanChecked = false;

    public ConfigPresenter(Context context, ConfigActivity iView) {
        super(context, iView);
        expandable = new ArrayList<>();
    }

    public void commit(String email, String password) {
        // 文本校验
        checkAccount(email, password);
        if (cancel) {
            return;
        }
        checkPermissionSettings();
        if (cancel) {
            return;
        }
        checkMall();
        if (cancel) {
            return;
        }
        // 完成文本校验后,显示
        showDetail(email, password);
    }

    private void showDetail(final String email, final String password) {

        StringBuilder detailMessage = new StringBuilder();
        detailMessage.append(" Email : ")
                .append(email)
                .append("\n")
                .append(" Password : ")
                .append(password)
                .append("\n")
                .append(" Permission : \n");
        if (isWifiChecked) {
            detailMessage.append("      Wifi")
                    .append("\n");
        }

        if (isBluetoothChecked) {
            detailMessage.append("      Blue")
                    .append("\n");
        }

        if (isMapChecked) {
            detailMessage.append("      Map")
                    .append("\n");
        }
        if (isRoutePlanChecked) {
            detailMessage.append("      Route Plan")
                    .append("\n");
        }

        detailMessage.append(" Malls : \n");

        for (Mall mall : ConfigActivity.selectModes) {
            detailMessage.append("      ").append(mall.getMallName()).append("\n");
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(context.getString(R.string.msg_detail_title))
                .setMessage(detailMessage.toString()).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                commitData(email, password);
            }
        }).create().show();
    }

    private void commitData(String email, String password) {

        final JSONObject param = new JSONObject();
        try {
            param.put("userPassword", MD5Util.parseStrToMd5L32(password));
            param.put("userName", email);
            param.put("wifi", isWifiChecked)
                    .put("bluetooth", isBluetoothChecked)
                    .put("map", isMapChecked)
                    .put("pathPlan", isRoutePlanChecked);

            JSONArray array = new JSONArray();
            for (Mall mall : ConfigActivity.selectModes) {
                array.put(mall.getMallId());
            }
            param.put("mallIds", array);

            Log.d("requestParams", param.toString());

            iView.showProgress();

            StringBuilder sb = new StringBuilder();

            sb.append(Config.BASE_IP).append("demo/v1.0/insertDemoData.do");//?jsonData=").append(param.toString()).append("&appKey=f4b5aeaa1776f7af714e0663fa2e50b2");

            Log.d("insertDemoData", sb.toString());
            Map<String, String> params = new HashMap<>();
            params.put("jsonData", param.toString());
            params.put("appKey", Config.APP_KEY);

            OkHttpClientManager.postAsyn(sb.toString(), params, new OkHttpClientManager.ResultCallback<String>() {
                @Override
                public void onError(Request request, Exception e) {
                    Log.e("error", e.getMessage());
                }

                @Override
                public void onResponse(String response) {
                    try {
                        ProgressDialogUtils.dismissProgressDialog(context);
                        final JSONObject resultJson = new JSONObject(response);

                        if (resultJson.getBoolean("isSuccess")) {
                            iView.showToast(context.getString(R.string.msg_upload_success));
                        } else {
                            try {
                                iView.showToast(resultJson.getString("msg"));
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        Log.d("result ", response);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void checkMall() {
        if (ConfigActivity.adapter.getCount() <= 0) {
            iView.showToast(context.getString(R.string.error_choose_mall));
            cancel = true;
        } else {
            cancel = false;
        }
    }

    private void checkPermissionSettings() {
        if (!(isWifiChecked || isBluetoothChecked || isMapChecked || isRoutePlanChecked)) {
            iView.showToast(context.getString(R.string.error_permission_select));
            cancel = true;
        } else {
            cancel = false;
        }
    }

    private void checkAccount(String email, String password) {

        if (!checkEmail(email)) {
            iView.setEmailError(context.getString(R.string.error_incorrect_password));
            cancel = true;
        } else {
            iView.setEmailError(null);
            cancel = false;
        }

        if (!checkPassword(password)) {
            iView.setPasswordError(context.getString(R.string.error_invalid_password));
            cancel = true;
        } else {
            iView.setEmailError(null);
            cancel = false;
        }
    }

    private boolean checkEmail(String email) {
        return !TextUtils.isEmpty(email) && email.contains("@") && email.endsWith(".com");
    }

    private boolean checkPassword(String password) {
        return !TextUtils.isEmpty(password) && password.length() > 6;
    }

    public void selectMall() {
        if (expandable.size() == 0) {
            iView.showToast("当前商场列表为空,请稍后再试或联系管理员!");
        } else {
            Intent intent = new Intent(context, MallListActivity.class);
            intent.putParcelableArrayListExtra("malls", expandable);
            iView.startActivityForResult(intent, REQUEST_CODE);
        }
    }

    public void getBuildingsByHttp() {

        StringBuilder getBuildings = new StringBuilder();
        getBuildings.append(Config.BASE_IP)
                .append("nexd/v1.0/map/getBuildings.do");
        Map<String, String> param = new HashMap<>();
        param.put("appKey", Config.APP_KEY);
        Log.d(TAG, getBuildings.toString());

        OkHttpClientManager.postAsyn(getBuildings.toString(), param, new OkHttpClientManager.ResultCallback<String>() {
            @Override
            public void onError(Request request, Exception e) {
                Log.d(TAG, "get buildings failed");
                e.printStackTrace();
            }

            @Override
            public void onResponse(String response) {
                if (response != null) {
                    JSONObject json;
                    try {
                        json = new JSONObject(response);
                        if (json.getBoolean("isSuccess")) {
                            JSONArray resultArray = json.getJSONArray("malls");
                            String lastCityName = "";

                            ArrayList<Mall> malls = null;
                            for (int i = 0; i < resultArray.length(); i++) {
                                JSONObject jsonObject = resultArray.getJSONObject(i);

                                if ("".equals(lastCityName)) {
                                    malls = new ArrayList<>();
                                    malls.add(new Mall(jsonObject.getString("buildingCode"), jsonObject.getString("cnName")));
                                    lastCityName = jsonObject.getString("cnCityName");
                                } else if (lastCityName.equals(jsonObject.getString("cnCityName"))) {
                                    if (malls != null) {
                                        malls.add(new Mall(resultArray.getJSONObject(i).getString("buildingCode"), resultArray.getJSONObject(i).getString("cnName")));
                                    }
                                } else {
                                    expandable.add(new Expandable(lastCityName, malls));
                                    malls = new ArrayList<>();
                                    malls.add(new Mall(jsonObject.getString("buildingCode"), jsonObject.getString("cnName")));
                                    lastCityName = jsonObject.getString("cnCityName");
                                }
                            }
                            expandable.add(new Expandable(lastCityName, malls));
                        }
                    } catch (JSONException e) {
                        iView.showToast(context.getString(R.string.error_data));
                        e.printStackTrace();
                    }
                } else {
                    iView.showToast(context.getString(R.string.error_data));
                }
            }
        });
    }


    private void data() {

        for (int j = 0; j < 10; j++) {
            expandable = new ArrayList<>();
            ArrayList<Mall> malls = new ArrayList<>();
            for (int i = 0; i < 30; i++) {
                malls.add(new Mall("" + (i + 1), "测试商场" + (i + 1)));
            }
            expandable.add(new Expandable("北京" + j, malls));
        }
    }

    public void setWifiChecked(boolean wifiChecked) {
        isWifiChecked = wifiChecked;
    }

    public void setBluetoothChecked(boolean bluetoothChecked) {
        isBluetoothChecked = bluetoothChecked;
    }

    public void setMapChecked(boolean mapChecked) {
        isMapChecked = mapChecked;
    }

    public void setRoutePlanChecked(boolean routePlanChecked) {
        isRoutePlanChecked = routePlanChecked;
    }

}
